<?php

namespace addons\zzyy\controller\api;

use addons\zzyy\module\Weixin;
use app\admin\model\zzyy\ZzyyThird;
use app\admin\model\zzyy\ZzyyUserExtend;
use fast\Http;
use fast\Random;
use think\Exception;
use think\Hook;
use think\Request;

class Login extends \app\common\controller\Api
{
    protected $noNeedLogin = ['*'];

    public function mpWeixinLogin()
    {
        if ($this->request->isPost()) {
            $code = $this->request->post('code', '');

            try {

                $res = Weixin::getInstance()->getSession($code);

                if (!isset($res['session_key'])) {
                    throw new Exception('session_key 未得到');
                }
                $sessionKey = $res['session_key'];
                $openid = $res['openid'];

            } catch (\Exception $e) {

                $this->error($e->getMessage());
            }

            //是否通过微信登录过
            $thirdUser = ZzyyThird::where('openid', $openid)->where('platform', ZzyyThird::PLATFORM_MP_WEIXIN)->find();

            if (is_null($thirdUser)) {
                $this->result('未注册用户', null, 2);
            } else {
                $user = \app\common\model\User::get($thirdUser->user_id);

                // 更新微信的sessionkey
                $thirdUser->sessionkey = $sessionKey;
                $thirdUser->save();

                // 登录
                if ($user->status != 'normal') {
                    $this->error('账号被锁，请联系管理员');
                }
                //如果已经有账号则直接登录
                $this->auth->keeptime(0);
                $ret = $this->auth->direct($user->id);
            }

            if ($ret) {
                $userInfo = \addons\zzyy\module\User::getUserInfo($user->id);
                $userInfo = array_merge($userInfo, ['token' => $this->auth->getToken()]);

                $this->success('登录成功', $userInfo);
            } else {
                $this->error($this->auth->getError());
            }

        }
        $this->error('need post request');
    }

    public function mpWeixinRegisterByProfileAndLogin()
    {
        if ($this->request->isPost()) {
            $code = $this->request->post('code', '');
            $nickName = $this->request->post('nickname', 'user_' . date('ymd') . Random::alnum(6));
            $avatar = $this->request->post('avatar', ''); ;
            $gender = 0;

            if (empty($code) or empty($nickName) or empty($avatar)) {
                $this->error('参数不完整');
            }

            try {
                $res = Weixin::getInstance()->getSession($code);
                if (!isset($res['session_key'])) {
                    throw new Exception('session_key 未得到');
                }
                $sessionKey = $res['session_key'];
                $openid = $res['openid'];

            } catch (\Exception $e) {

                $this->error($e->getMessage());
            }

            // 注册和登录
            $thirdUser = ZzyyThird::where('openid', $openid)->where('platform', ZzyyThird::PLATFORM_MP_WEIXIN)->find();

            // 注册
            if (is_null($thirdUser)) {
                Hook::add('user_register_successed', function ($param) use ($openid, $nickName, $avatar, $gender, $sessionKey) {
                    ZzyyThird::create([
                        'user_id' => $param->id,
                        'platform' => ZzyyThird::PLATFORM_MP_WEIXIN,
                        'openid' => $openid,
                        'openname' => $nickName,
                        'sessionkey' => $sessionKey,
                    ]);
                    $param->nickname = $nickName;
                    $param->avatar = $avatar;
                    $param->gender = $gender;
                    $param->save();

                    ZzyyUserExtend::create([
                        'user_id' => $param->id,
                    ]);

                });
                $ret = $this->auth->register(ZzyyThird::PLATFORM_MP_WEIXIN . Random::alnum(), Random::alnum());
            } else {
                $user = \app\common\model\User::get($thirdUser->user_id);

                // 更新微信的sessionkey
                $thirdUser->sessionkey = $sessionKey;
                $thirdUser->save();

                // 登录
                if ($user->status != 'normal') {
                    $this->error('账号被锁，请联系管理员');
                }
                //如果已经有账号则直接登录
                $this->auth->keeptime(0);
                $ret = $this->auth->direct($thirdUser->id);
            }

            if ($ret) {
                $user = $this->auth->getUserinfo();
                $userInfo = \addons\zzyy\module\User::getUserInfo($user['id']);
                $userInfo = array_merge($userInfo, ['token' => $this->auth->getToken()]);

                $this->success('登录成功', $userInfo);
            } else {
                $this->error($this->auth->getError());
            }

        }
        $this->error('need post request');

    }

    public function getPhoneByCode()
    {
        $code = $this->request->get('code');
        $code = "d3df33e2645c477354e618fc2605d09ae74605caf350a60696730a2661f8a5ec";
        $token = Weixin::getInstance()->minProgram()->access_token->getToken();
        $token = $token['access_token'];

        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$token";

        $headers = ['content-type:application/json'];
        $options = [
            CURLOPT_HTTPHEADER => $headers
        ];

        $res = Http::post($url, json_encode(['code' => $code]), $options);
        var_dump($res);

    }

}
